/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.axon.config;

import org.axonframework.eventhandling.saga.repository.SagaStore;
import org.axonframework.eventhandling.tokenstore.TokenStore;
import org.axonframework.eventsourcing.eventstore.EventStorageEngine;
import org.axonframework.mongo.MongoTemplate;
import org.axonframework.mongo.eventhandling.saga.repository.MongoSagaStore;
import org.axonframework.mongo.eventsourcing.eventstore.MongoEventStorageEngine;
import org.axonframework.mongo.eventsourcing.eventstore.documentperevent.DocumentPerEventStorageStrategy;
import org.axonframework.mongo.eventsourcing.tokenstore.MongoTokenStore;
import org.axonframework.serialization.Serializer;
import org.axonframework.serialization.upcasting.event.EventUpcaster;
import org.axonframework.spring.config.AxonConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@ConditionalOnBean(MongoTemplate.class)
@Configuration
public class MongoAutoConfiguration {

    @ConditionalOnMissingBean
    @Bean
    public EventStorageEngine eventStorageEngine(MongoTemplate mongoTemplate, Serializer serializer,
                                                 AxonConfiguration configuration) {
        return new MongoEventStorageEngine(serializer, configuration.getComponent(EventUpcaster.class),
                mongoTemplate, new DocumentPerEventStorageStrategy());
    }

    @ConditionalOnMissingBean
    @Bean
    public TokenStore tokenStore(MongoTemplate mongoTemplate, @Qualifier("tokenSerializer") Serializer serializer) {
        return new MongoTokenStore(mongoTemplate, serializer);
    }

    @ConditionalOnMissingBean(SagaStore.class)
    @Bean
    public SagaStore sagaStore(MongoTemplate mongoTemplate, Serializer serializer) {
        return new MongoSagaStore(mongoTemplate, serializer);
    }

}
